
import { Form, Input, Button, Checkbox } from 'antd';
import { UserWrapper } from './StyledUser';
import { useDispatch } from 'react-redux'

import { login as setToken } from '../../store/actions/login.js';
import { login } from '../../api/user.js';
import { useHistory } from 'react-router-dom';

import { useIntl, FormattedMessage } from '../../components/LangSelect';

// dispatch(actionCreator.changeSwitch(false))
const layout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};
const tailLayout = {
  wrapperCol: { offset: 8, span: 16 },
};

const Login = () => {
  const intl = useIntl();
  const history = useHistory();
  const { search } = history.location;
  const query = new URLSearchParams(search);
  const dispatch = useDispatch();

  const onFinish = (values: any) => {
    console.log('Success:', values);

    const {username, password, remember} = values; 
    login({username, password}).then((res:any)=>{
      if (remember) {
        localStorage.setItem('user', JSON.stringify({username, password}))
      }
      const token = res.data.token
      dispatch(setToken(token))

      history.replace({
        pathname: query?.get("redirect") || '/'
      });
    }).catch((err: any) => {
      console.log(err)
    })
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };

  return (
    <UserWrapper>
      <div className="form-wrapper">
        <h2><FormattedMessage
          id="login.logIn"
          defaultMessage="登 录"
        /></h2>
        <Form
          {...layout}
          name="basic"
          initialValues={{ remember: true }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
        >
          <Form.Item
            label={intl.formatMessage({id: "login.username", defaultMessage: "用户名"})} 
            name="username" rules={[{ required: true, message: 'Please input your username!' }]}
          >
            <Input value="admin"/>
          </Form.Item>

          <Form.Item
            label={intl.formatMessage({id: "login.password", defaultMessage: "密 码"})}
            name="password"
            rules={[{ required: true, message: 'Please input your password!' }]}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item {...tailLayout}
            name="remember" 
            valuePropName="checked"
            rules={[
              {
                validator: (_, value) =>
                  value ? Promise.resolve() : Promise.reject(new Error('Should accept agreement')),
              },
            ]}
          >
            <Checkbox style={{lineHeight: '32px'}}>
              <FormattedMessage id="remember" /></Checkbox>
          </Form.Item>
          
          <Form.Item {...tailLayout}>
            <Button type="primary" htmlType="submit">
              <FormattedMessage id="submit" />
            </Button>
            <Button type="link" href="/register"><FormattedMessage id="login.register" /></Button>
          </Form.Item>
        </Form>
      </div>
    </UserWrapper>
  );
};

export default Login;
